/*
 * 文件名：BaseController.java
 * 版权：Copyright by http://www.zy-iot.com
 * 描述：
 * 修改人：yangl
 * 修改时间：2015年12月12日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.softa.web.controller.base;

import com.softa.annotation.CurrentUser;
import com.softa.bean.Tree;
import com.softa.cache.util.RedisUitl;
import com.softa.dao.model.SysFile;
import com.softa.dao.model.SysUser;
import com.softa.enummodel.FileTypeEnum;
import com.softa.service.system.ResourceService;
import com.softa.exception.BusinessException;
import com.softa.enummodel.ResponseErrorEnum;
import com.softa.service.system.SysFileService;
import com.softa.utils.Constants;
import com.softa.utils.ResponseUtil;
import com.softa.vo.QueryRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomBooleanEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;

public class BaseController {
	 /**本地异常日志记录对象  */
    protected static  final Logger logger = LoggerFactory.getLogger(BaseController.class);
    
    @Resource
    private ResourceService resourceService;

    @Resource
    private SysFileService sysFileService;

    @Autowired
    private RedisUitl redisUitl;

    @ModelAttribute("sysname")
    public String getSysname() throws IOException {
        Object obj = redisUitl.get("sysname");
        if(null != obj){
            return (String) obj;
        }else{
            return Constants.getSysname();
        }
    }

    @ModelAttribute("menus")
    public List<Tree> resourceResource(@CurrentUser SysUser loginUser) {
//        return userService.findResourceList(loginUser.getUsername());
    	if(loginUser==null){
    		return Collections.EMPTY_LIST;
    	}
    	return  resourceService.findMenuResourceTree(loginUser.getUsername());
    }

    @ModelAttribute("pic")
    public Long userHeadPic(@CurrentUser SysUser loginUser) {
        if(null == loginUser){
            return 0l;
        }
        QueryRequest queryRequest = new QueryRequest();
        queryRequest.getParams().put("pkeyId", loginUser.getId().toString());
        queryRequest.getParams().put("tableName", SysUser.class.getSimpleName());
        queryRequest.getParams().put("fileType", FileTypeEnum.IMAGE.toString());
        SysFile sysFile = sysFileService.selectOneByCondition(queryRequest);
        if (null != sysFile) {
            return sysFile.getId();
        }else{
            return 0l;
        }
    }

    // 转换器
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                dateFormat, false));

        binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor("1",
                "0", true));
    }

    @ExceptionHandler(BusinessException.class)
    public void businessExceptionHandler(BusinessException ex,
                                         HttpServletResponse response, HttpServletRequest request)
            throws IOException {
        // 业务错误
        System.out.println("【web端】捕捉到业务错误：" + ex.getMessage());
        ResponseUtil.responseError(response, "\"" + ex.getMessage() + "\"",
                ResponseErrorEnum.ServiceError);
    }

    @ExceptionHandler(ValidationException.class)
    public void validationExceptionHandler(ValidationException ex,
                                           HttpServletResponse response, HttpServletRequest request)
            throws IOException {
        // 业务错误
        System.out.println("【web端】捕捉到验证错误：" + ex.getMessage());
        ResponseUtil.responseError(response, "\"" + ex.getMessage() + "\"",
                ResponseErrorEnum.ValidateDataError);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public void ViolationExceptionHandler(ConstraintViolationException ex,
                                          HttpServletResponse response, HttpServletRequest request)
            throws IOException {
        // 参数错误

        Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
        int size = violations.size();
        String[] errString = new String[size];
        int i = 0;
        for (ConstraintViolation<?> x : violations) {
            errString[i++] = x.getMessage();
        }

        System.out.println("【web端】捕捉到参数错误：" + errString);
        ResponseUtil.responseError(response, errString,
                ResponseErrorEnum.ValidateDataError);
    }
}
